/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode* root) {
        vector<TreeNode*> t;
        ListTree(root, t);
        int n = t.size();
        for (int i = 1; i < n; ++i) {
            TreeNode *prev = t.at(i - 1), *curr = t.at(i);
            prev->left = nullptr;
            prev->right = curr;
        }
    }
    void ListTree(TreeNode* root, vector<TreeNode*>& t) {
        if (root == nullptr)
            return;
        t.push_back(root);
        ListTree(root->left, t);
        ListTree(root->right, t);
    }
};
